package com.zhangtai.modules.service.impl.employee;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.zhangtai.consts.CommonConstr;
import com.zhangtai.modules.dao.EmployeeInfoDao;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.service.employee.EmployeeInfoService;
import com.zhangtai.modules.vo.RegularVo;
import com.zhangtai.utils.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.dynamic.scaffold.InstrumentedType;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.transform.Templates;
import java.util.*;


@RestController
@Slf4j
public class EmployeeInfoServiceImpl extends ServiceImpl<EmployeeInfoDao, EmployeeInfoEntity> implements EmployeeInfoService {

    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    private EmployeeInfoDao employeeInfoDao;

    @Override
    public PageResult queryPage(@RequestParam(value = "employeeOid", required = false) String employeeOid,
                                @RequestParam(value = "name", required = false) String name,
                                @RequestParam(value = "orgname", required = false) List<Long> orgname,
                                @RequestParam(value = "unitname", required = false) List<Long> unitname,
                                @RequestParam(value = "jobname", required = false) List<Long> jobname,
                                @RequestParam(value = "status", required = false) List<Integer> status,
                                @RequestParam(value = "isReinstate", required = false) Integer isReinstate,
                                @RequestParam(value = "isEntryStatus", required = false) Integer isEntryStatus,
                                @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
            , @RequestParam(value = "orgIds") List<Long> orgIds,
                                @RequestParam(value = "socialTrainee", required = false) Integer socialTrainee
            ,
                                @RequestParam(value = "isOffer", required = false) Integer isOffer,
                                @RequestParam(value = "isSendContract", required = false) Integer isSendContract,
                                @RequestParam(value = "userCode", required = false) String userCode
    ) {

        Integer i = 0;
        ArrayList<Integer> integers = new ArrayList<>();
        integers.add(0);
        integers.add(1);
        integers.add(3);
        QueryWrapper<EmployeeInfoEntity> employeeWrapper = new QueryWrapper<EmployeeInfoEntity>()
                .like(!StringUtils.isEmpty(name), "name", name).in(!CollectionUtils.isEmpty(orgname), "org_id", orgname)
                .eq(orgname != null && orgname.size() == 0, "org_id", null).eq(unitname != null && unitname.size() == 0, "unit_id", unitname)
                .eq(jobname != null && jobname.size() == 0, "job_id", null)
                .in(!CollectionUtils.isEmpty(unitname), "unit_id", unitname).in(!CollectionUtils.isEmpty(jobname), "job_id", jobname)
                .eq("is_delete", 0).eq(isReinstate != null, "is_reinstate", isReinstate).eq(isEntryStatus != null, "is_entry_status", isEntryStatus)
                .eq(!StringUtils.isEmpty(employeeOid), "employee_oid", employeeOid)
                .eq(!ObjectUtils.isEmpty(socialTrainee), "social_trainee", socialTrainee)
                .in(!CollectionUtils.isEmpty(status), "status", status)
                .eq(isEntryStatus != null, "is_entry_status", isEntryStatus)
                .in("is_reinstate", integers)
//                .le(hireDate!=null&&i.equals(isEntryStatus),"hiredate",hireDate)
                .eq(isOffer != null, "is_offer", isOffer)
                .eq(!ObjectUtils.isEmpty(isSendContract), "is_send_contract", isSendContract);
        employeeWrapper.and(wra -> wra.in(!CollectionUtils.isEmpty(orgIds), "unit_id", orgIds).or().
                eq("principal_user_code", userCode).or().eq(CollectionUtils.isEmpty(orgIds), "unit_id", null)).orderByDesc("hiredate");
        IPage<EmployeeInfoEntity> page = this.page(
                new Page<EmployeeInfoEntity>(pageNum, pageSize), employeeWrapper
        );

        return new PageResult(page);
    }

    @Override
    public PageResult findBySalaryBran(@RequestParam(value = "keyword", required = false) String keyword,
                                       @RequestParam(value = "orgIds", required = false) List<Long> orgIds,
                                       @RequestParam(value = "code", required = false) String code,
                                       @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                       @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {


        ArrayList<Integer> integers = new ArrayList<>();
        integers.add(0);
        integers.add(1);
        integers.add(3);
        QueryWrapper<EmployeeInfoEntity> queryWrapper = new QueryWrapper<EmployeeInfoEntity>()
                .eq("is_delete", 0).in(!ObjectUtils.isEmpty(orgIds), "org_id", orgIds)
                .eq(ObjectUtils.isEmpty(orgIds), "org_id", null).in("is_reinstate", integers).
                        or().eq(CollectionUtils.isEmpty(orgIds), "org_id", null)
                .orderByDesc("create_time");

//        queryWrapper.and(wra->wra.in(!CollectionUtils.isEmpty(orgIds),"unit_id",orgIds).or().
//                eq("principal_user_code",code).or().eq(CollectionUtils.isEmpty(orgIds),"unit_id",null)) .orderByDesc("create_time");
        IPage<EmployeeInfoEntity> page = this.page(
                new Page<EmployeeInfoEntity>(pageNum, pageSize),
                queryWrapper
        );

        return new PageResult(page);
    }

    @Override
    public PageResult queryEmployeePage(@RequestParam(value = "name", required = false) String name,
                                        @RequestParam(value = "orgIds", required = false) List<Long> orgIds,
                                        @RequestParam(value = "code", required = false) String code,
                                        @RequestParam(value = "orgname", required = false) List<Long> orgname,
                                        @RequestParam(value = "unitname", required = false) List<Long> unitname,
                                        @RequestParam(value = "jobname", required = false) List<Long> jobname,
                                        @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                        @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {


        QueryWrapper<EmployeeInfoEntity> queryWrapper = new QueryWrapper<EmployeeInfoEntity>()
                .eq("is_delete", 0)
                .like(!StringUtils.isEmpty(name), "name", name)
                .like(!StringUtils.isEmpty(code), "code", code)
                .in(!CollectionUtils.isEmpty(orgname), "org_id", orgname)
                .in(!CollectionUtils.isEmpty(orgIds), "unit_id", orgIds)
                .eq(CollectionUtils.isEmpty(orgIds), "unit_id", null)
                .in(!CollectionUtils.isEmpty(unitname), "unit_id", unitname)
                .in(!CollectionUtils.isEmpty(jobname), "job_id", jobname);

        IPage<EmployeeInfoEntity> page = this.page(
                new Page<EmployeeInfoEntity>(pageNum, pageSize),
                queryWrapper
        );

        return new PageResult(page);
    }


    @Override
    public R deleteSalaryBandMonitoring(@RequestParam("id") Long id) {
        EmployeeInfoEntity employeeInfoEntity = new EmployeeInfoEntity();
        employeeInfoEntity.setOid(id);
        employeeInfoEntity.setSalaryBandMonitoringIsDelete(1);
        boolean b = this.updateById(employeeInfoEntity);
        if (!b) {
            return R.error();
        }
        return R.ok();
    }

    @Override
    public PageResult<EmployeeInfoEntity> getRegularList(@RequestBody RegularVo regularVo, List<Long> lineSystem,
                                                         List<Long> jobSystem, List<Long> orgIds,
                                                         List<Long> org, List<Long> unit, List<Long> job) {
        String name = regularVo.getName();

        List<Integer> isRegular = regularVo.getIsRegular();
        Integer dealStatus = regularVo.getDealStatus();
        Integer isDistribute = regularVo.getIsDistribute();
        Boolean flag = regularVo.getFlag();
//        String jobName = regularVo.getJobName();
        List<Integer> regularBpmStatus = regularVo.getRegularBpmStatus();
        ArrayList<Integer> integers = new ArrayList<>();
        integers.add(0);
        integers.add(1);
        integers.add(3);
        QueryWrapper<EmployeeInfoEntity> queryWrapper = new QueryWrapper<EmployeeInfoEntity>().like(!StringUtils.isEmpty(name), "name", name)
                .in(!CollectionUtils.isEmpty(isRegular), "is_regular", isRegular).eq(dealStatus != null, "deal_status", dealStatus)
                .eq(isDistribute != null, "is_distribute", isDistribute)
                .eq("is_delete", 0).in("is_reinstate", integers)
                .in(!CollectionUtils.isEmpty(regularBpmStatus), "regular_bpm_status", regularBpmStatus)
                .in(!ObjectUtils.isEmpty(lineSystem), "line_id", lineSystem).in(!ObjectUtils.isEmpty(jobSystem), "job_system_id", jobSystem)
                .eq("is_entry_status", 1).le(flag != null && flag, "regular_day", DateUtils.addDateDays(new Date(), -20))
                //查询转正未处理数据时不显示离职人员
                .ne(flag != null && flag, "employeestatus", 3)
                //不查询实习生
                .ne("employeestatus", "9")
                .in(!CollectionUtils.isEmpty(org), "org_id", org)
                .eq(org != null && org.size() == 0, "org_id", null)
                .in(!CollectionUtils.isEmpty(unit), "unit_id", unit)
                .eq(unit != null && unit.size() == 0, "unit_id", null)
                .in(!CollectionUtils.isEmpty(job), "job_id", job)
                .eq(job != null && job.size() == 0, "job_id", null);
        queryWrapper.and(wra -> wra.in(!CollectionUtils.isEmpty(orgIds), "unit_id", orgIds).or().
                eq("principal_user_code", regularVo.getCode()).or().eq(CollectionUtils.isEmpty(orgIds), "unit_id", null)).orderByAsc("regular_day");

        IPage<EmployeeInfoEntity> page = this.page(
                new Page<EmployeeInfoEntity>(regularVo.getPageNum(), regularVo.getPageSize()),
                //is_reinstate 0:新员工，1离职未满一年，3离职超过一年   ，social_trainee：0社招
                queryWrapper
        );

        return new PageResult(page);

    }


    @Override
    public List<EmployeeInfoEntity> getRegularListReport(@RequestBody RegularVo regularVo, List<Long> lineSystem,
                                                         List<Long> jobSystem, List<Long> orgIds,
                                                         List<Long> org, List<Long> unit, List<Long> job) {
        String name = regularVo.getName();

        List<Integer> isRegular = regularVo.getIsRegular();
        Integer dealStatus = regularVo.getDealStatus();
        Integer isDistribute = regularVo.getIsDistribute();
        Boolean flag = regularVo.getFlag();
//        String jobName = regularVo.getJobName();
        List<Integer> regularBpmStatus = regularVo.getRegularBpmStatus();
        ArrayList<Integer> integers = new ArrayList<>();
        integers.add(0);
        integers.add(1);
        integers.add(3);
        QueryWrapper<EmployeeInfoEntity> queryWrapper = new QueryWrapper<EmployeeInfoEntity>().like(!StringUtils.isEmpty(name), "name", name)
                .in(!CollectionUtils.isEmpty(isRegular), "is_regular", isRegular).eq(dealStatus != null, "deal_status", dealStatus)
                .eq(isDistribute != null, "is_distribute", isDistribute)
                .eq("is_delete", 0).in("is_reinstate", integers)
                .in(!CollectionUtils.isEmpty(regularBpmStatus), "regular_bpm_status", regularBpmStatus)
                .in(!ObjectUtils.isEmpty(lineSystem), "line_id", lineSystem).in(!ObjectUtils.isEmpty(jobSystem), "job_system_id", jobSystem)
                .eq("is_entry_status", 1).le(flag != null && flag, "regular_day", DateUtils.addDateDays(new Date(), -20))
                //查询转正未处理数据时不显示离职人员
                .ne(flag != null && flag, "employeestatus", 3)
                //不查询实习生
                .ne("employeestatus", "9")
                .in(!CollectionUtils.isEmpty(org), "org_id", org)
                .eq(org != null && org.size() == 0, "org_id", null)
                .in(!CollectionUtils.isEmpty(unit), "unit_id", unit)
                .eq(unit != null && unit.size() == 0, "unit_id", null)
                .in(!CollectionUtils.isEmpty(job), "job_id", job)
                .eq(job != null && job.size() == 0, "job_id", null);
        queryWrapper.and(wra -> wra.in(!CollectionUtils.isEmpty(orgIds), "unit_id", orgIds).or().
                eq("principal_user_code", regularVo.getCode()).or().eq(CollectionUtils.isEmpty(orgIds), "unit_id", null)).orderByAsc("regular_day");

        List<EmployeeInfoEntity> page = employeeInfoDao.selectList(queryWrapper);


        return page;

    }

    @Override
    public PageResult queryPageIsDistribute(@RequestParam(value = "isDistribute", required = false) Integer isDistribute,
                                            @RequestParam(value = "orgIds", required = false) List<Long> orgIds,
                                            @RequestParam(value = "code", required = false) String code,
                                            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        QueryWrapper<EmployeeInfoEntity> queryWrapper = new QueryWrapper<EmployeeInfoEntity>().eq(isDistribute != null, "is_distribute", isDistribute)
                .eq("is_delete", 0);
        queryWrapper.and(wra -> wra.in(!CollectionUtils.isEmpty(orgIds), "unit_id", orgIds).or().
                eq("principal_user_code", code).or().eq(CollectionUtils.isEmpty(orgIds), "unit_id", null)).orderByDesc("create_time");
        IPage<EmployeeInfoEntity> page = this.page(
                new Page<EmployeeInfoEntity>(pageNum, pageSize),
                queryWrapper
        );

        return new PageResult(page);
    }

    @Override
    public PageResult findHireListPage(@RequestParam(value = "keyword", required = false) String keyword,
                                       @RequestParam(value = "status", required = false) List<Integer> status,
                                       @RequestParam(value = "isReinstate", required = false) Integer isReinstate,
                                       @RequestParam(value = "code", required = false) String code,
                                       @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                       @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                       @RequestParam(value = "orgIds") List<Long> orgIds) {
        ArrayList<Integer> integers = new ArrayList<>();
        integers.add(0);
        integers.add(1);
        integers.add(3);
        QueryWrapper<EmployeeInfoEntity> queryWrapper = new QueryWrapper<EmployeeInfoEntity>().like(!StringUtils.isEmpty(keyword), "name", keyword)
                .eq("is_delete", 0).eq(isReinstate != null, "is_reinstate", isReinstate).
                        in(!CollectionUtils.isEmpty(status), "status", status).in("is_reinstate", integers) //jin展示0:新员工，1：复职员工离职未满一年，3：复职员工离职超过一年
                .orderByDesc("update_time");
        queryWrapper.and(wra -> wra.in(!CollectionUtils.isEmpty(orgIds), "unit_id", orgIds).or().
                eq("principal_user_code", code).or().eq(CollectionUtils.isEmpty(orgIds), "unit_id", null)).orderByDesc("update_time");
        IPage<EmployeeInfoEntity> page = this.page(
                new Page<EmployeeInfoEntity>(pageNum, pageSize),
                queryWrapper
        );
//        只提取 预计入职时间与当前时间小于15天的
        ArrayList<EmployeeInfoEntity> employeeInfoEntities = new ArrayList<>();
        for (EmployeeInfoEntity record : page.getRecords()) {
            Date hiredate = record.getHiredate();
            Integer integer = DateUtils.daysBetween(new Date(), hiredate);
            if (integer <= CommonConstr.BEFORE_HIRE_DAYS && integer >= 0) {
                employeeInfoEntities.add(record);
            }

        }
        page.setRecords(employeeInfoEntities);

        return new PageResult(page);

    }

    @Override
    public EmployeeInfoEntity getByIdE(Long id) {
        EmployeeInfoEntity one = this.getOne(new QueryWrapper<EmployeeInfoEntity>().eq("oid", id));

        return one;
    }

    @Override
    @Transactional
    public R saveE(EmployeeInfoEntity entity) {
        boolean b = this.save(entity);
        if (!b) {
            return R.error();
        }
        return R.ok();

    }

    @Override
    public R updateByIdE(EmployeeInfoEntity entity) {
        String code = entity.getCode();

        boolean b = this.updateById(entity);
        if (!b) {
            return R.error();
        }
        return R.ok();
    }

    @Override
    public R removeOneById(Long id) {
        EmployeeInfoEntity entity = new EmployeeInfoEntity();
        entity.setOid(id);
        entity.setIsDelete(1);
        boolean b = this.updateById(entity);
        if (!b) {
            return R.error();
        }
        return R.ok();
    }

    @Override
    @Transactional
    public R removeByIdsE(List<Long> ids) {
        for (Long id : ids) {
            R r = removeOneById(id);
            if (!r.getFlag()) {
                return r;
            }
        }
        return R.ok();
    }

    /**
     * 通过员工状态获取员工信息
     *
     * @return
     * @Description:
     * @params 0:待发起 ，1：已发起待审批，2：审批完成，3：作废,
     * @Author: czw
     * @CreateDate: 2021/3/15 10:22
     */
    public EmployeeInfoEntity getEmployeeInfoByRegularBpmStatus(List<Integer> status, Long oid) {
        return this.getOne(new QueryWrapper<EmployeeInfoEntity>().eq("oid", oid).in("regular_bpm_status", status));
    }

    /**
     * 查询员工信息
     *
     * @param orgname
     * @param name
     * @param unitname
     * @param pageNum
     * @param
     * @return
     */
    @Override
    public PageUtils getAllEmployeeInfos(String orgname, String name, String unitname, String pageNum, String pageSize, String curPage,String jobname) {

                IPage<EmployeeInfoEntity> page = getEmployeeInfoEntityIPage(orgname, name, unitname, pageNum, pageSize, curPage, jobname);
                PageUtils pageUtils = new PageUtils(page);
                return pageUtils;

    }

    /**
     * 从数据库查询员工信息
     * @param orgname
     * @param name
     * @param unitname
     * @param pageNum
     * @param pageSize
     * @param curPage
     * @param jobname
     * @return
     */
    private IPage<EmployeeInfoEntity> getEmployeeInfoEntityIPage(String orgname, String name, String unitname, String pageNum, String pageSize, String curPage, String jobname) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("orgname", orgname);
        map.put("unitname", unitname);
        map.put("pageNum", pageNum);
        map.put("page", curPage);
        map.put("limit", pageSize);
        map.put("jobname", jobname);
        QueryWrapper<EmployeeInfoEntity> wapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(name)) {
            wapper.like("name", "%" + name + "%");
        }
        if (!StringUtils.isEmpty(unitname)) {
            wapper.like("unitname", "%" + unitname + "%");
        }
        if (!StringUtils.isEmpty(orgname)) {
            wapper.like("orgname", "%" + orgname + "%");
        }
        if (!StringUtils.isEmpty(jobname)) {
            wapper.like("jobname", "%" + jobname + "%");
        }
        IPage<EmployeeInfoEntity> page = this.page(new Query<EmployeeInfoEntity>().getPage(map), wapper);
        return page;
    }

    @Test
    public void test() {
        Date date = DateUtils.addDateDays(new Date(), 2);
        Integer integer = DateUtils.daysBetween(new Date(), date);
        System.out.println(integer);
    }


}